import Api, { GET_CATE, GET_HOT_CATE_GOODS, GET_CHILD_CATE} from '../../utils/api.js';
import {handPic,getUrl} from '../../utils/util.js';


const App = getApp();
Page({
    data: {
        sort_index: "",
        keyword: '',
        top_cate: [], //顶级分类
        child_cate:[],
        hot_goods:[]
    },

    onLoad: function () {
        const that = this;


        Api.fetch(GET_CATE, {}, resp => {
            resp.child_cate.map((v,k) => {
                v.img = handPic(v.img,4)
            })

            resp.hot_goods.map((v,k) => {
                v.default_img = handPic(v.default_img,8) 
            })
            this.setData({
                top_cate: resp.top_cate,
                sort_index : resp.top_cate[0]['id'],
                child_cate: resp.child_cate,
                hot_goods : resp.hot_goods,
            })
        })

    
    },
    // 设置不同分类数据请求
    setSortIndex: function (e) {
        const that = this;
        let { hot_goods, child_cate, sort_index } = this.data;

        const idx = e.target.dataset.idx

        // 点击请求别的分类数据时,先清空当前数据,改状态为正在加载中
        if (sort_index != idx) {

            wx.showLoading({
                title: '数据加载中',
                mask:true
            })
            Api.fetch(GET_CHILD_CATE,{gc_id:idx},resp=>{
                resp.child_cate.map((v, k) => {
                    v.img = handPic(v.img, 4)
                })

                resp.hot_goods.map((v, k) => {
                    v.default_img = handPic(v.default_img, 8)
                })

                this.setData({
                    child_cate:resp.child_cate,
                    hot_goods:resp.hot_goods,
                    sort_index:idx
                })
                wx.hideLoading();
            })
        }
    },

    // 通用页面跳转
    navigateTo: function (e) {
        let url;
        const tip = e.target.dataset.tip;
        const idx = e.target.dataset.idx;

   
        const {keyword} = this.data;
        
        if (tip == 'goods_detail') {
            url = getUrl(tip,{gc_id:idx});
        } else if (tip == 'search') {
            url = `../search/search?keyword=${keyword}`;
        } else if (tip == 'sub_sort') {
            // 缺少相关参数 
            url = `../special/special?cateid=${idx}`;
        }

        App.navigateTo(url);
    }
    // 页面加载

})